// API相关的组合式函数
import { ref, type Ref } from 'vue'
import type { ApiResponse } from '@/types'

/**
 * 通用API请求Hook
 */
export function useApi<T = unknown>() {
  const loading = ref(false)
  const error = ref<string | null>(null)
  const data = ref<T | null>(null)

  const execute = async (
    request: () => Promise<{ data: ApiResponse<T> }>
  ): Promise<T | null> => {
    try {
      loading.value = true
      error.value = null

      const response = await request()
      data.value = response.data.data

      return response.data.data
    } catch (err) {
      error.value = err instanceof Error ? err.message : '请求失败'
      return null
    } finally {
      loading.value = false
    }
  }

  return {
    loading: loading as Ref<boolean>,
    error: error as Ref<string | null>,
    data: data as Ref<T | null>,
    execute
  }
}
